package skdao

import (
	"Cgo/backend/models"
	"Cgo/global"
	"errors"
)

type userDao struct{}

var UserDao = userDao{}

// 添加用户
func (u userDao) AddUser(id int, name string, password string) error {
	// 执行数据库插入操作
	if result := global.DB.Exec("INSERT INTO sk_user (id, name, password) VALUES (?, ?, ?)", id, name, password); result.Error != nil {
		return result.Error
	} else {
		return nil
	}
}

// 修改用户信息
func (u userDao) UpdateUser(name string, newName string, newPassword string) error {
	// 检查用户是否存在
	var userInfo models.SkUser
	if r := global.DB.Raw("SELECT * FROM sk_user WHERE name = ?", name).Scan(&userInfo); r.RowsAffected == 0 {
		return errors.New("用户不存在")
	}

	// 更新用户信息
	global.DB.Exec("UPDATE sk_user SET name = ?, password = ? WHERE name = ?", newName, newPassword, name)

	return nil
}

// 删除用户
func (u userDao) DeleteUser(id int) error {
	if r := global.DB.Exec("DELETE FROM sk_user WHERE id = ?;", id); r.Error != nil {
		return r.Error
	} else {
		return nil
	}
}

// GetUsers 用于获取所有用户信息(刷新)
func (u userDao) GetUsers() ([]models.SkUser, error) {
	var users []models.SkUser
	if err := global.DB.Table("sk_user").Find(&users).Error; err != nil {
		return nil, err
	}
	return users, nil
}
